package com.qire.common.support.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.qire.common.utils.EquipmentInfoUtil;

public class BasePopupMenu extends PopupWindow {

    protected View mRootView;
    protected Context mContext;

    protected int mWidth=0,mHeight=0;

    public BasePopupMenu(Context context, int layoutResource, int width, int height){
        super(LayoutInflater.from(context).inflate(layoutResource, null, true));
        mContext = context;
        mWidth   = width;
        mHeight  = height;
        setFocusable(true);//控件锁定焦点
    }

    public BasePopupMenu(Context context) {
        this(context,0,0);
    }

    public BasePopupMenu(Context context, int width, int height) {
        super(context);
        mContext = context;
        mWidth   = width;
        mHeight  = height;
        setFocusable(true);//控件锁定焦点
    }

    public void setContentView(int layoutResource) {
        setContentView(LayoutInflater.from(mContext).inflate(layoutResource, null, true));
    }

    @Override
    public void setContentView(View contentView) {
        super.setContentView(contentView);
        mRootView = contentView;
        init();
    }

    private void init(){

        int unspecified,width,height;

        unspecified = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        mRootView.measure(unspecified, unspecified);

        width   = EquipmentInfoUtil.getScreenWidth();
        height  = EquipmentInfoUtil.getScreenHeight();
        width   = mWidth  !=0 ? mWidth  : width;
        height  = mHeight !=0 ? mHeight : height;
        setWidth(width);
        setHeight(height);

        //遮罩透明
//		WindowManager.LayoutParams params=ac.getWindow().getAttributes();
//      params.alpha=0.7f;

        this.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

//		contentView.setFocusableInTouchMode(true);

//        这里是处理如果菜单布局边框获得焦点的情况，一般不按按钮按其他地方需要关闭菜单，
//        这里因为菜单关闭需要处理键盘打开的问题，所以不启用了
        mRootView.setOnTouchListener((view, event) -> {
            if(isShowing()) {
                dismiss();
            }
            return false;
        });
    }

    @Override
    public void showAsDropDown(View anchor) {
        setHeight(EquipmentInfoUtil.getScreenHeight() - anchor.getBottom());
        super.showAsDropDown(anchor);
    }

}
